package m2;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws Exception{
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672); //默认端口可以不用设置
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection(); //连接
        Channel c = con.createChannel(); //通道
        //创建队列
        c.queueDeclare("helloworld1",false,false,false,null);
        //创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                byte[] a = delivery.getBody();
                String s1 = new String(a,"UTF-8");
                System.out.println("收到： "+s1);
                // 模拟阻塞的消息  遍历字符串找 ‘.’ 每找到一个暂停一秒
                for (int i = 0; i < s1.length(); i++) {
                    if ('.'==s1.charAt(i)){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //发送回执   回执，是否同时确认多条消息
                c.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                System.out.println(delivery.getEnvelope().getDeliveryTag());
                System.out.println("-------------消息处理完毕\n");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        c.basicQos(1);
        //开始接收消息，收到的消息会传递到一个回调对象进行处理
        // autoAck=true 自动确认  =false 手动确认
        c.basicConsume("helloworld1",false,deliverCallback,cancelCallback);
    }
}
